package filter;

import entity.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

public class CheckLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        User user = new User() ;
        HttpServletRequest request = (HttpServletRequest) req ;
        HttpServletResponse response = (HttpServletResponse) resp ;
        HttpSession session = request.getSession() ;
        user = (User)session.getAttribute("user") ;
        String uri = request.getRequestURI() ;
        if(uri.equals("/sign-up.html")){
//            System.out.println("这里表示你在登录页面");
            chain.doFilter(request , response);
            return ;
        }
        if(Objects.isNull(user)){
            System.out.println("经过了检查登录的过滤器");
            String path = request.getContextPath() ;
            response.sendRedirect(path + "/sign-up.html");
        }else{
            System.out.println("这里表示已登录");
            chain.doFilter(request , response);
        }

    }

    @Override
    public void destroy() {

    }
}
